package cn.mumzone.pos.ui.widgets.schedule;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import cn.mumzone.basic.util.AppDateUtil;
import cn.mumzone.basic.util.ListUtil;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.pos.R;
import cn.mumzone.pos.ui.widgets.others.FullyGridLayoutManager;

/**
 * 排班自定义日历控件
 *
 */
public class ScheduleView extends LinearLayout {

    private RecyclerView mRvTheMonth;

    private RecyclerView mRvNextMonth;

    private ArrayList<ScheduleEntity> mTheMonthList;

    private ArrayList<ScheduleEntity> mNextMonthList;

    private ADA_Schedule mTheMonthAdapter;

    private ADA_Schedule mNextMonthAdapter;

    private OnDateItemClickListener mOnDateItemClickListener;

    private String mSelectedDate;

    private boolean notScheduleEnable = true;

    public ScheduleView(Context context) {
        this(context, null);
    }

    public ScheduleView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);

        LayoutInflater.from(context).inflate(R.layout.view_schedule, this);

        mRvTheMonth = findViewById(R.id.rv_the_month);
        mRvNextMonth = findViewById(R.id.rv_next_month);

        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.setTimeInMillis(System.currentTimeMillis());

        //仅展示当月和下月的日期
        int month = calendar.get(Calendar.MONTH) + 1;
        TextView tvTheMonth = findViewById(R.id.tv_the_month);
        tvTheMonth.setText(String.format("%s月", month));
        TextView tvNextMonth = findViewById(R.id.tv_next_month);
        tvNextMonth.setText(String.format("%s月", month != 12 ? month + 1 : 1));

        initData();
    }

    private void initData() {

        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.setTimeInMillis(System.currentTimeMillis());
//        calendar.setTimeInMillis(AppDateUtil.getStringToDate("2019-03-01","yyyy-MM-dd"));
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        mTheMonthList = new ArrayList<>();

        //计算第一个月份，第一周的情况下，需要填充的空白格子
        //转换Monday开头的日期Index （Calendar默认获取Sunday开头日期Index）
        int mondayStartIndex = calendar.get(Calendar.DAY_OF_WEEK) - 1 == 0 ? 7 : calendar.get(Calendar.DAY_OF_WEEK) - 1;

        //总补空缺数
        int sumDiff = mondayStartIndex - 1;

        //开始日期 日期为第一周 直接取1号为开始日期
        int startDay = day < sumDiff ? 1 : day - sumDiff;

        //日期补空缺数
        int dayDiff = day - startDay;

        //空白补空缺
        int nullDiff = sumDiff - dayDiff;

        //补充空白数据
        for (int index = 0; index < nullDiff; index++) {
            mTheMonthList.add(new ScheduleEntity());
        }

        //补充剩余数据
        for (int index = startDay; index <= calendar.getActualMaximum(Calendar.DAY_OF_MONTH); index++) {
            ScheduleEntity scheduleEntity = new ScheduleEntity();
            scheduleEntity.setDate(String.format("%s-%s-%s", year, getFormatDate(month), getFormatDate(index)));
            if (index == day) {
                mSelectedDate = String.format("%s-%s-%s", year, getFormatDate(month), getFormatDate(index));
                scheduleEntity.setChecked(true);
            }
            mTheMonthList.add(scheduleEntity);
        }


        if (month == 12) {
            month = 1;
            year++;
        } else {
            month++;
        }
        calendar.clear();
        calendar.setTimeInMillis(AppDateUtil.getStringToDate(String.format("%s-%s-%s", year, month, 1), "yyyy-MM-dd"));

        mNextMonthList = new ArrayList<>();


        //转换Monday开头的日期Index （Calendar默认获取Sunday开头日期Index）
        int nextMonthStartIndex = calendar.get(Calendar.DAY_OF_WEEK) - 1 == 0 ? 7 : calendar.get(Calendar.DAY_OF_WEEK) - 1;

        //总补空缺数
        int nextNullDiff = nextMonthStartIndex - 1;


        //补充空白数据
        for (int index = 0; index < nextNullDiff; index++) {
            mNextMonthList.add(new ScheduleEntity());
        }

        //补充日期
        for (int index = 1; index <= calendar.getActualMaximum(Calendar.DAY_OF_MONTH); index++) {
            ScheduleEntity scheduleEntity = new ScheduleEntity();
            scheduleEntity.setDate(String.format("%s-%s-%s", year, getFormatDate(month), getFormatDate(index)));
            mNextMonthList.add(scheduleEntity);
        }


        mRvTheMonth.setLayoutManager(new FullyGridLayoutManager(getContext(), 7));
        mRvNextMonth.setLayoutManager(new FullyGridLayoutManager(getContext(), 7));
        mRvTheMonth.setHasFixedSize(true);
        mRvNextMonth.setHasFixedSize(true);
        mRvTheMonth.setNestedScrollingEnabled(false);
        mRvNextMonth.setNestedScrollingEnabled(false);

        mTheMonthAdapter = new ADA_Schedule(getContext());
        mTheMonthAdapter.setDataList(mTheMonthList);
        mTheMonthAdapter.setNotScheduleEnable(notScheduleEnable);
        mRvTheMonth.setAdapter(mTheMonthAdapter);
        mTheMonthAdapter.setOnItemClickListener(new ADA_Schedule.OnItemClickListener() {
            @Override
            public void onItemClicked(int position) {
                String date = mTheMonthAdapter.getDataList().get(position).getDate();
                mSelectedDate = date;
                if (mOnDateItemClickListener != null) {
                    mOnDateItemClickListener.onDateItemClicked(date);
                }
                if (mNextMonthAdapter != null) {
                    mNextMonthAdapter.clearCheck();
                }
            }
        });


        mNextMonthAdapter = new ADA_Schedule(getContext());
        mNextMonthAdapter.setDataList(mNextMonthList);
        mNextMonthAdapter.setNotScheduleEnable(notScheduleEnable);
        mRvNextMonth.setAdapter(mNextMonthAdapter);
        mNextMonthAdapter.setOnItemClickListener(new ADA_Schedule.OnItemClickListener() {
            @Override
            public void onItemClicked(int position) {
                String date = mNextMonthAdapter.getDataList().get(position).getDate();
                mSelectedDate = date;
                if (mOnDateItemClickListener != null) {
                    mOnDateItemClickListener.onDateItemClicked(date);
                }
                if (mTheMonthAdapter != null) {
                    mTheMonthAdapter.clearCheck();
                }
            }
        });

    }

    public void setNotScheduleEnable(boolean notScheduleEnable) {
        this.notScheduleEnable = notScheduleEnable;
        mTheMonthAdapter.setNotScheduleEnable(notScheduleEnable);
        mNextMonthAdapter.setNotScheduleEnable(notScheduleEnable);
    }

    private String getFormatDate(int dayOrMonth) {
        if (dayOrMonth < 10) {
            return String.format("0%s", dayOrMonth);
        }
        return String.valueOf(dayOrMonth);
    }

    public void setScheduleStatus(List<String> entityList) {

        ArrayList<String> scheduleList = new ArrayList<>();
        if (!ListUtil.isListEmpty(entityList)) {
            scheduleList.addAll(entityList);

        }

        for (ScheduleEntity scheduleEntity : mTheMonthList) {
            if (!scheduleList.isEmpty() && scheduleList.contains(scheduleEntity.getDate())) {
                scheduleEntity.setScheduled(true);
            } else {
                scheduleEntity.setScheduled(false);
            }
        }
        for (ScheduleEntity scheduleEntity : mNextMonthList) {
            if (!scheduleList.isEmpty() && scheduleList.contains(scheduleEntity.getDate())) {
                scheduleEntity.setScheduled(true);
            } else {
                scheduleEntity.setScheduled(false);
            }
        }
        mTheMonthAdapter.notifyDataSetChanged();
        mNextMonthAdapter.notifyDataSetChanged();
    }

    public void setSelectedDate(String selectedDate) {
        this.mSelectedDate = selectedDate;
        for (ScheduleEntity entity : mTheMonthAdapter.getDataList()) {
            if (!StringUtils.isEmpty(entity.getDate()) && entity.getDate().equals(selectedDate)) {
                entity.setChecked(true);
            } else {
                entity.setChecked(false);
            }
        }
        mTheMonthAdapter.notifyDataSetChanged();
    }

    public void clearCheck() {
        mTheMonthAdapter.clearCheck();
        mNextMonthAdapter.clearCheck();
    }


    public String getSelectedDate() {
        return mSelectedDate;
    }

    public void setOnDateItemClickListener(OnDateItemClickListener onDateItemClickListener) {
        this.mOnDateItemClickListener = onDateItemClickListener;
    }

    public interface OnDateItemClickListener {
        void onDateItemClicked(String date);
    }
}
